package bb.lanxing.databinding.utils;

import android.content.Context;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.view.View;
import androidx.core.content.ContextCompat;

public class SpanClickHelper {
    private ClickSpanListener clickSpanListener;
    private Context context;

    public interface ClickSpanListener {
        boolean drawUnderLine();

        int getColor();

        void onClick(String str);
    }

    public SpanClickHelper(Context context, ClickSpanListener clickSpanListener) {
        this.clickSpanListener = clickSpanListener;
        this.context = context;
    }

    private void setLinkClickable(SpannableStringBuilder spannableStringBuilder, final URLSpan uRLSpan) {
        spannableStringBuilder.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View view) {
                String url = uRLSpan.getURL();
                if (SpanClickHelper.this.clickSpanListener != null) {
                    SpanClickHelper.this.clickSpanListener.onClick(url);
                }
            }

            @Override
            public void updateDrawState(TextPaint textPaint) {
                if (SpanClickHelper.this.clickSpanListener != null) {
                    textPaint.setColor(ContextCompat.getColor(SpanClickHelper.this.context, SpanClickHelper.this.clickSpanListener.getColor()));
                    textPaint.setUnderlineText(SpanClickHelper.this.clickSpanListener.drawUnderLine());
                    return;
                }
                super.updateDrawState(textPaint);
            }
        }, spannableStringBuilder.getSpanStart(uRLSpan), spannableStringBuilder.getSpanEnd(uRLSpan), spannableStringBuilder.getSpanFlags(uRLSpan));
    }

    public CharSequence getClickableHtml(CharSequence charSequence) {
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(charSequence);
        for (URLSpan uRLSpan : (URLSpan[]) spannableStringBuilder.getSpans(0, charSequence.length(), URLSpan.class)) {
            setLinkClickable(spannableStringBuilder, uRLSpan);
        }
        return spannableStringBuilder;
    }
}
